<template>
  <div class="page-container">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-row">
            <h2 class="page-title">用户管理</h2>
            <div class="search-bar">
              <el-input
                v-model="searchUsername"
                placeholder="输入用户名模糊查询"
                clearable
                class="search-input"
                @keyup.enter="searchUsers"
              >
                <template #append>
                  <el-button @click="searchUsers" icon="search" />
                </template>
              </el-input>
              <el-button
                type="primary"
                @click="fetchUsers"
                plain
                class="action-button"
              >
                重置
              </el-button>
              <el-button
                type="success"
                @click="showAddDialog"
                class="action-button"
              >
                <el-icon><plus /></el-icon>新增用户
              </el-button>
            </div>
          </div>
        </div>
      </template>

      <el-table
        :data="accountList"
        border
        style="width: 100%"
        class="data-table"
        v-loading="loading"
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" min-width="100px"/>
        <el-table-column prop="email" label="邮箱" min-width="180px"/>
        <el-table-column prop="phone" label="电话" min-width="150px"/>
        <el-table-column prop="gender" label="性别" min-width="90px">
          <template #default="{ row }">
            {{ formatGender(row.gender) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="注册时间" min-width="200"/>
        <el-table-column prop="role" label="角色" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.role === 'admin' ? 'danger' : ''">
              {{ row.role || 'user' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enabled" label="启用状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.enabled ? 'success' : 'danger'" effect="dark">
              {{ row.enabled ? '已启用' : '已禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="showEditDialog(row)" type="primary" plain>
                编辑
              </el-button>
              <el-button size="small" type="danger" @click="handleDelete(row.id)" plain>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      class="user-dialog"
    >
      <el-form
        :model="currentUser"
        label-width="100px"
        label-position="left"
        :rules="formRules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="currentUser.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="currentUser.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="currentUser.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="currentUser.gender" style="width: 100%">
                <el-option label="男" value="M" />
                <el-option label="女" value="F" />
                <el-option label="未知" value="U" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="isAddMode">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="currentUser.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="currentUser.confirmPassword"
                type="password"
                placeholder="请确认密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="currentUser.role" style="width: 100%">
                <el-option label="管理员" value="admin" />
                <el-option label="普通用户" value="user" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="enabled">
              <el-switch
                v-model="currentUser.enabled"
                active-text="启用"
                inactive-text="禁用"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" size="medium">取消</el-button>
          <el-button type="primary" @click="submitForm" size="medium">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import userApi from '@/api/users'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { checkEmail } from '@/api/auth'
const accountList = ref([])
const loading = ref(false)
const searchUsername = ref('')
const dialogVisible = ref(false)
const isAddMode = ref(true)

const currentUser = ref({
  id: null,
  username: '',
  email: '',
  phone: '',
  gender: 'U',
  password: '',
  confirmPassword: '',
  role: 'user',
  enabled: true
})

const validatePass2 = (formRules, value, callback) => {
  if (value !== currentUser.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validateEmail = async (formRules, value, callback) => {
  if (!value) {
    callback(new Error('请输入邮箱地址'))
    return
  }

  // 邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
    return
  }

  // 编辑模式下不需要验证邮箱是否已存在
  if (!isAddMode.value) {
    callback()
    return
  }

  try {
    const response = await checkEmail(value)
    if (response.exists) {
      callback(new Error('该邮箱已被注册'))
    } else {
      callback()
    }
  } catch (error) {
    callback(new Error('邮箱验证失败'))
  }
}

const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: ['blur', 'change'] }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
}

const dialogTitle = computed(() => isAddMode.value ? '新增用户' : '编辑用户')

const formatGender = (gender) => {
  switch (gender) {
    case 'M': return '男'
    case 'F': return '女'
    case 'U': return '未知'
    default: return gender || '未知'
  }
}

// 获取全部用户
const fetchUsers = async () => {
  loading.value = true
  searchUsername.value = ''
  try {
    const data = await userApi.getUsers()
    accountList.value = data
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}
// 替换 fetchUserById 方法
const searchUsers = async () => {
  if (!searchUsername.value.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }

  loading.value = true
  try {
    const users = await userApi.searchByUsername(searchUsername.value)
    accountList.value = users
    if (users.length === 0) {
      ElMessage.warning('未找到匹配的用户')
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
  } finally {
    loading.value = false
  }
}

// 显示新增对话框
const showAddDialog = () => {
  isAddMode.value = true
  currentUser.value = {
    id: null,
    username: '',
    email: '',
    phone: '',
    gender: 'U',
    password: '',
    confirmPassword: '',
    role: 'user',
    enabled: true
  }
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (user) => {
  isAddMode.value = false
  currentUser.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    phone: user.phone,
    gender: user.gender || 'U',
    password: '',
    confirmPassword: '',
    role: user.role,
    enabled: user.enabled
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    if (isAddMode.value) {
      await userApi.createUser({
        username: currentUser.value.username,
        email: currentUser.value.email,
        phone: currentUser.value.phone,
        gender: currentUser.value.gender,
        password: currentUser.value.password,
        role: currentUser.value.role,
        enabled: currentUser.value.enabled
      })
      ElMessage.success('用户创建成功')
    } else {
      await userApi.updateUser(currentUser.value.id, {
        username: currentUser.value.username,
        email: currentUser.value.email,
        phone: currentUser.value.phone,
        gender: currentUser.value.gender,
        role: currentUser.value.role,
        enabled: currentUser.value.enabled
      })
      ElMessage.success('用户更新成功')
    }
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除用户
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该用户吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(async () => {
    try {
      await userApi.deleteUser(id)
      ElMessage.success('用户删除成功')
      fetchUsers()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }).catch(() => {
  })
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.main-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  white-space: nowrap;
  margin-right: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-grow: 1;
  justify-content: flex-end;
}

.search-input {
  width: 260px;
}

.action-button {
  white-space: nowrap;
  padding: 8px 15px;
}

.data-table {
  margin-top: 15px;
  border-radius: 8px;
  overflow: hidden;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.user-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

.user-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 20px;
}

@media (max-width: 768px) {
  .header-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .search-bar {
    width: 100%;
    justify-content: flex-start;
  }

  .search-input {
    width: 100%;
  }
}
</style>
